﻿using System;
using System.Collections;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEngine;
using UnityEngine.UI;

public class MonsterHealth : MonoBehaviour
{
    public static Action OnMonsterKilled;          //-------------------------------


    [SerializeField] private GameObject healthBarPrefab;
    [SerializeField] private Transform barPosition;

    [SerializeField] private float initialHealth = 10f;
    [SerializeField] private float maxHealth = 10f;

    public float CurrentHealth { get; set; }

    private Image _healthBar;
    private Monster _monster;
    // Start is called before the first frame update
    void Start()
    {
        _monster = GetComponent<Monster>();
        CreateHealthBar();
        CurrentHealth = initialHealth;
    }

    private void Update()
    {
        
        //if (Input.GetKeyDown(KeyCode.P))
        //{
        //    DealDamage();
        //}

        _healthBar.fillAmount = Mathf.Lerp(_healthBar.fillAmount, CurrentHealth / maxHealth, Time.deltaTime * 10f);
        //Mathf.Lerp 函数接受三个参数：起始值、目标值和插值因子。它返回一个在起始值和目标值之间插值的结果。
        //在这里，起始值是 _healthBar.fillAmount，目标值是 CurrentHealth / maxHealth，插值因子是 Time.deltaTime * 10f。
    }

    private void CreateHealthBar()
    {
        GameObject newBar = Instantiate(healthBarPrefab, barPosition.position, Quaternion.identity);
        newBar.transform.SetParent(transform);

        MonsterHealthContainer container = newBar.GetComponent<MonsterHealthContainer>();
        _healthBar = container.FillAmountImage;
    }

    //public void DealDamage()
    //{
    //    CurrentHealth -= attackDamage;
     //   IEnumerator DelayedExecution()
      //  {
          //  yield return new WaitForSeconds(_animator.GetCurrentAnimatorStateInfo(0).length+0.5f);
            // 在这里执行需要延迟的代码
            //if (CurrentHealth <= 0)
           // {
            //    CurrentHealth = 0;
           //     Die();
           // }
      //  }
        // 启动协程
      //  StartCoroutine(DelayedExecution());
    //}

    public void ResetHealth()
    {
        CurrentHealth = initialHealth;
        _healthBar.fillAmount = 1f;
    }

    private void Die()
    {
        ResetHealth();
        OnMonsterKilled?.Invoke();
        ObjectPooler.ReturnToPool(gameObject);
        MoneyManager.Money += _monster.GetMoney;
    }
}
